import { hrmResignApi } from "@/api/HRMS/Resign/index";
import { thStaffsGetStaffsList } from "@/api/system/user";
import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { message } from "antd";
import { useTranslation } from "react-i18next";
let reload: Function;
let pkId: string;
let staffId: string;
const timeFn = (time: string) => {
	if (!time) {
		return "";
	}
	const [date] = time.split(" ");
	return date;
};
const index = (props: { register: Fn }) => {
	const { t } = useTranslation();
	const ev_vi = "HRMS.retired";
	const formSchema: FormSchema[] = [
		{
			label: t(`${ev_vi}.staffName`),
			field: "staffName", //姓名
			component: "ApiSelect",
			componentProps: {
				api: thStaffsGetStaffsList,
				labelField: "staffName",
				valueField: "staffName",
				onChange: (_: any, value: any) => {
					if (!value) return;
					staffId = value.staffId;
				}
			}
		},
		{
			label: t(`${ev_vi}.timeToWork`),
			field: "startDate", //参加工作时间
			component: "DatePicker"
		},
		{
			label: t(`${ev_vi}.retirementTime`),
			field: "endDate", //退休时间
			component: "DatePicker"
		}
	];
	const [registerDrawer, { closeDrawer }] = useDrawerInner(props.register, data => {
		console.log(data);
		reload = data.reload;
		resetFields();
		if (data.record) {
			pkId = data.record.pkId;
			staffId = data.record.staffId;
			setFieldsValue(data.record);
		}
	});

	const [register, { validateFields, setFieldsValue, resetFields }] = useForm({
		schemas: formSchema,
		labelWidth: 100,
		baseColProps: {
			span: 24
		}
	});
	const handleSubmit = async () => {
		let formValue = await validateFields();
		let api = hrmResignApi.hrmResignCreate;
		formValue = {
			...formValue,
			staffId
		};
		if (pkId) {
			api = hrmResignApi.hrmResignUpdate;
		}
		formValue.startDate = timeFn(formValue.startDate);
		formValue.endDate = timeFn(formValue.endDate);
		const res = await api({ ...formValue, pkId });
		if (res) {
			pkId ? message.success(t("kevin_ui.updateSuccess")) : message.success(t("kevin_ui.addedSuccessfully"));
			closeDrawer();
			reload();
		}
	};
	return (
		<BasicDrawer showFooter={true} {...props} register={registerDrawer} ok={handleSubmit}>
			<BasicForm register={register}></BasicForm>
		</BasicDrawer>
	);
};
export default index;
